package com.lecyon.farm.config;

import com.lecyon.farm.comment.JwtToken;
import com.lecyon.farm.comment.JwtUtil;
import com.lecyon.farm.common.constant.CommonConstant;
import com.lecyon.farm.entity.JsSysUser;
import com.lecyon.farm.service.impl.AuthenticationService;
import com.lecyon.farm.util.RedisUtils;
import com.lecyon.farm.util.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author Yao Zheng
 * @Date 2019/9/5 15:15
 */
@Slf4j
@Service
public class CustomerRealm extends AuthorizingRealm {

    private AuthenticationService authenticationService;

    private RedisUtils redisUtils;

    private HttpSession httpSession;

    @Autowired
    public CustomerRealm(AuthenticationService authenticationService, RedisUtils redisUtils) {
        super();
        this.authenticationService = authenticationService;
        this.redisUtils = redisUtils;
    }

    @Autowired
    public void setHttpSession(HttpSession httpSession) {
        this.httpSession = httpSession;
    }

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 认证.登录
     *
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String sysUserId = JwtUtil.getSysUserId(token);
        if (StringHelper.isEmpty(sysUserId)) {
            throw new AuthenticationException("令牌无效");
        }
        Map<String, Object> redisHash;
        String account = null;
        StringBuffer key = new StringBuffer();
        key.append(CommonConstant.SYSTEM_NAME).append(CommonConstant.SYSTEM_SPLIT_STR).append(token);
        String tokenKey = key.toString();
        if (!redisUtils.hasKey(tokenKey)) {
            throw new AuthenticationException("令牌已过期");
        }
        key.delete(0, key.length());
        key.append(CommonConstant.SYSTEM_NAME).append(CommonConstant.SYSTEM_SPLIT_STR).append(sysUserId);
        String sysUserKey = key.toString();
        if (redisUtils.hasKey(sysUserKey)) {
            redisHash = redisUtils.hmGet(sysUserKey);
            account = (String) redisHash.get(CommonConstant.CONTEXT_KEY_USER_ID);
        }
        if (StringHelper.isEmpty(account)) {
            throw new AuthenticationException("令牌已过期");
        } else if (!sysUserId.equals(account)) {
            throw new AuthenticationException("令牌无效");
        } else {
            redisUtils.expire(sysUserId, CommonConstant.MAX_REDIS_TOKEN_STORAGE_TIME);
            redisUtils.expire(token, CommonConstant.MAX_REDIS_TOKEN_STORAGE_TIME);
        }
        return new SimpleAuthenticationInfo(token, token, getName());
    }

    /**
     * 授权
     *
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        String token = (String) principal.getPrimaryPrincipal();
        principal.getRealmNames();
        String username = JwtUtil.getUsername(token);
        JsSysUser sysUser = authenticationService.findUserByUserName(username);
//        List<String> permissions = authenticationService.getUserPermissionListByUserName(username);
        List<String> rolesName = authenticationService.getUserRoleNameListByUserName(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //将角色放入shiro中
        info.addRoles(rolesName);
        //将权限放入shiro中
//        info.addStringPermissions(permissions);
        return info;
    }

}
